<?php
/* Activate a users account */
$usererrors = array();

//Get token param
if(isset($_GET["nuevo"]))
{		
    $token = $_GET["nuevo"];

    if(!isset($token))
    {
        $usererrors[] = lang("FORGOTPASS_INVALID_TOKEN");
    }
    else if(!validateActivationToken($token)) //Check for a valid token. Must exist and active must be = 0
    {
        $usererrors[] = lang("FORGOTPASS_INVALID_TOKEN");
    }
    else
    {
        //Activate the users account
        if(!setUserActive($token))
        {
            $usererrors[] = lang("SQL_ERROR");
        } else {
            $success_message  = lang("ACCOUNT_NOW_ACTIVE");
        }

    }
}
else
//User has confirmed they want their password changed
//----------------------------------------------------------------------------------------------
if(!empty($_GET["confirmar"]))
{
    $token = trim($_GET["confirmar"]);

    if($token == "" || !validateActivationToken($token,TRUE))
    {
        $usererrors[] = lang("FORGOTPASS_INVALID_TOKEN");
    }
    else
    {
        $rand_pass = getUniqueCode(15);
        $secure_pass = generateHash($rand_pass);

        $userdetails = fetchUserDetails(NULL,$token);

        $mail = new userCakeMail();

        //Setup our custom hooks
        $hooks = array(
                        "searchStrs" => array("#GENERATED-PASS#","#USERNAME#"),
                        "subjectStrs" => array($rand_pass,$userdetails["Username"])
        );

        if(!$mail->newTemplateMsg("your-lost-password.txt",$hooks))
        {
            $usererrors[] = lang("MAIL_TEMPLATE_BUILD_ERROR");
        }
        else
        {
            if(!$mail->sendMail($userdetails["Email"],"Tu nueva clave en cos.as"))
            {
                $usererrors[] = lang("MAIL_ERROR");
            }
            else
            {
                if(!updatePasswordFromToken($secure_pass,$token))
                {
                    $usererrors[] = lang("SQL_ERROR");
                }
                else
                {
                    //Might be wise if this had a time delay to prevent a flood of requests.
                    flagLostPasswordRequest($userdetails["Username_Clean"],0);

                    $success_message  = lang("FORGOTPASS_NEW_PASS_EMAIL");
                }
            }
        }
    }
}

//----------------------------------------------------------------------------------------------

//User has denied this request
//----------------------------------------------------------------------------------------------
if(!empty($_GET["cancelar"]))
{
    $token = trim($_GET["cancelar"]);

    if($token == "" || !validateActivationToken($token,TRUE))
    {
        $usererrors[] = lang("FORGOTPASS_INVALID_TOKEN");
    }
    else
    {
        $userdetails = fetchUserDetails(NULL,$token);

        flagLostPasswordRequest($userdetails['Username_Clean'],0);

        $success_message = lang("FORGOTPASS_REQUEST_CANNED");
    }
}

if (!!isUserLoggedIn()) {
    $createUser = false;
    if(isset($_GET["twitter"]))
    {
        $back = trim($_GET["twitter"])=="back";

        $req_url = 'https://twitter.com/oauth/request_token';
        $authurl = 'https://twitter.com/oauth/authenticate';
        $acc_url = 'https://twitter.com/oauth/access_token';
        $api_url = 'http://api.twitter.com/1/account/verify_credentials.json';

        $oauth=new OAuth(TWITTER_CONS_KEY,TWITTER_CONS_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);

        if(!$back) {
            // fetch a request token
            $request_token_info = $oauth->getRequestToken($req_url, TWITTER_CALLBACK_URL);
            // persist the token to storage
            $_SESSION["TWITTER_TOKEN_SECRET"] = $request_token_info['oauth_token_secret'];
            // redirect the user
            header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
            exit;
        } else {
            if (!isset($_SESSION["TWITTER_TOKEN_SECRET"]))
                $usererrors[] = lang("TWITTER_INVALID_PROCESS");
            else {
                if (isset($_GET['denied'])) {
                    $usererrors[] = lang("TWITTER_DENIED_PROCESS");
                } else {
                    $oauth->setToken($_GET['oauth_token'],$_SESSION['TWITTER_TOKEN_SECRET']);
                    $access_token_info = $oauth->getAccessToken($acc_url);
                    $_SESSION['TWITTER_TOKEN'] = $access_token_info['oauth_token'];
                    $_SESSION['TWITTER_SECRET'] = $access_token_info['oauth_token_secret'];
                    $oauth->setToken($_SESSION['TWITTER_TOKEN'],$_SESSION['TWITTER_SECRET']);
                    $oauth->fetch($api_url);
                    $oauthuser = json_decode($oauth->getLastResponse());

                    $username = $oauthuser->screen_name;
                    $email = $oauthuser->id."@twitter";

                    //Construct a user object
                    $user = new User($username,$email,$email,true);

                    //Checking this flag tells us whether there were any errors such as possible data duplication occured
                    if(!$user->status) {
                        $usererrors[] = lang("TWITTER_INVALID_PROCESS");
                    }
                    //Attempt to add the user to the database
                    elseif($user->userID==null && !$user->userCakeAddUser()) {
                        $usererrors[] = lang("TWITTER_INVALID_PROCESS");
                    } else {
                        // Now that we have an Access Token, we can discard the Request Token
                        $_SESSION["TWITTER_TOKEN_SECRET"] = null;

                        $createUser = true;

                        $success_message = lang("TWITTER_SUCCESFULL_LOGIN");
                    }
                }
            }
        }
    }

    if(isset($_GET["facebook"]))
    {
        $back = trim($_GET["facebook"])=="back";

        $oauth=new OAuth(FACEBOOK_CONS_KEY,FACEBOOK_CONS_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);

        $siteurl = 'http://www.facebook.com/dialog/oauth';
        $acc_url = 'https://graph.facebook.com/oauth/access_token';
        $api_url = 'https://graph.facebook.com/me';

        if(!$back) {
            header("Location: $siteurl?client_id=".FACEBOOK_CONS_KEY."&redirect_uri=".urlencode(FACEBOOK_CALLBACK_URL));
            exit;
        } else {
            try {
                $code = $_GET['code'];
                if ($code==null)
                {
                    $error = $_GET['error'];
                    if ($error=="user_denied")
                    {
                        $usererrors[] = lang("FACEBOOK_DENIED_PROCESS");
                    } else {
                        $usererrors[] = lang("FACEBOOK_INVALID_PROCESS");
                    }
                } else {
                    $access_url = "$acc_url?client_id=".FACEBOOK_CONS_KEY."&redirect_uri=".urlencode(FACEBOOK_CALLBACK_URL)."&client_secret=".FACEBOOK_CONS_SECRET."&code=".urlencode($code);
                    $access_token_info = $oauth->getAccessToken($access_url);
                    $oauth->fetch($api_url."?".http_build_query($access_token_info));
                    $oauthuser = json_decode($oauth->getLastResponse());
                    if (strstr($oauthuser->link, "profile.php?id=")===false && ($username = strrchr($oauthuser->link, "/"))!==false )
                    {
                        $username = substr($username, 1);
                    } else {
                        $username = $oauthuser->name;
                    }
                    $email = $oauthuser->id."@facebook";

                    //Construct a user object
                    $user = new User($username,$email,$email,true);

                    //Checking this flag tells us whether there were any errors such as possible data duplication occured
                    if(!$user->status) {
                        $usererrors[] = lang("FACEBOOK_INVALID_PROCESS");
                    }
                    //Attempt to add the user to the database
                    elseif($user->userID==null && !$user->userCakeAddUser()) {
                        $usererrors[] = lang("FACEBOOK_INVALID_PROCESS");
                    } else {
                        $createUser = true;
                        $success_message = lang("FACEBOOK_SUCCESFULL_LOGIN");
                    }
                }
            }
            catch (Exception $e)
            {
                $usererrors[] = lang("FACEBOOK_INVALID_PROCESS");
            }
        }
    }

    if ($createUser)
    {
        $loggedInUser = new loggedInUser();
        $loggedInUser->email = $user->clean_email;
        $loggedInUser->user_id = $user->userID;
        $loggedInUser->hash_pw = $user->password_hash;
        $loggedInUser->display_username = $user->unclean_username;
        $loggedInUser->clean_username = $user->clean_username;

        //Update last sign in
        $loggedInUser->updateLastSignIn();

        $_SESSION["userCakeUser"] = $loggedInUser;
    }
}

if (count($usererrors)>0) {
    foreach ($usererrors as $error)
        $alert.="<p>$error</p>";
    $onload.="dlg(dalert);";
} elseif (isset($success_message)) {
    $alert=$success_message;
    $onload.="dlg(dalert);";
}